import React, { useRef, useEffect } from 'react';
import {
    PlusOutlined,
} from '@ant-design/icons';
import {
    Button,
    Input,
    message,
    Popconfirm,
    // Badge
    // Tag, Space,
    // Menu, Dropdown
} from 'antd';
import { connect } from 'react-redux'
import { useCustomState } from '@/hooks/useEffect';
import YzhTable from '@com/YzhTable';
import AddRoleDialog from './add'
import {
    hasPermission,
    permissionCodes as pCodes
} from '@/routes/permission'
import api from '@/api/apiList'

const { TextArea } = Input
const RoleManage = (props) => {
    const actionRef = useRef();
    let clientHeight = document.body.clientHeight
    const columns = [
        {
            title: '角色名称',
            dataIndex: 'name',
            hideInSearch: true,
            // sorter: true,
            width: 400,
            align: 'left',
            formItemProps: {
                placeholder: '角色名称',
                rules: [
                    {
                        required: true,
                        message: '角色名称为必填项',
                    },
                ],
            },
            renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
                if (type === 'form') {
                    return <Input
                        // 组件的配置
                        {...fieldProps}
                        // 自定义配置
                        key="roleName"
                        placeholder="请输入角色名称"
                    />;
                }
                return null
            },
        },
        {
            title: '角色名称',
            dataIndex: 'name',
            // copyable: true,
            ellipsis: true,
            // sorter: true,
            hideInTable: true,
            // tip: '名称/编码',
            renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
                if (type === 'form') {
                    return null;
                }
                return (
                    // value 和 onchange 会通过 form 自动注入。
                    <Input
                        // 组件的配置
                        {...fieldProps}
                        // 自定义配置
                        key="roleName"
                        placeholder="请输入角色名称"
                    />
                );
            },
        },
        {
            title: '角色介绍',
            dataIndex: 'description',
            hideInSearch: true,
            ellipsis: true,
            width: 600,
            renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
                if (type === 'form') {
                    return <TextArea
                        // 组件的配置
                        {...fieldProps}
                        // 自定义配置
                        maxLength={100}
                        key="description"
                        placeholder="请输入角色名称，最多100个字"
                    />;
                }
                return (
                    // value 和 onchange 会通过 form 自动注入。
                    null
                );
            },
            // sorter: true
        },
        {
            title: '创建时间',
            key: 'showTime',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            sorter: true,
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateRange',
            hideInSearch: true,
            hideInTable: true,
            search: {
                transform: (value) => {
                    return {
                        startTime: value[0],
                        endTime: value[1],
                    };
                },
            },
        },
        {
            title: '操作',
            valueType: 'option',
            align: 'center',
            fixed: 'right',
            width: 300,
            render: (text, record, _, action) => [
                (hasPermission([pCodes.role.edit]) && <a key="editable" type="link" onClick={() => {
                    let _a;
                    (_a = action === null || action === void 0 ? void 0 : action.startEditable) === null || _a === void 0 ? void 0 : _a.call(action, record.id);
                }}>
                    编辑
                </a>),
                (hasPermission([pCodes.role.remove]) && <Popconfirm
                    key="delete"
                    placement="topRight"
                    title={<p key="desc" style={{ maxWidth: 200 }}>删除后已绑定该角色的用户，不再可使用该角色的功能权限和数据权限，是否确认删除？</p>}
                    onConfirm={() => onDelete(record, action)}
                >
                    <a type="link" key="delete">
                        删除
                    </a>
                </Popconfirm>),
                (hasPermission([pCodes.role.authority]) && <a type="link" onClick={() => props.addTabs({ title: '权限配置', activeKey: '/userCenter/access', query: { id: record.id, name: record.name } }, props.history)} rel="noopener noreferrer" key="view">
                    权限配置
                </a>),
            ],
        },
    ];
    const [scroll,
        setScroll
    ] = useCustomState(props.scroll || { x: 1500, y: clientHeight });
    const [state, setState] = useCustomState({
        form: {
            description: '',
            id: '',
            name: ''
        },
        dialogAddVisible: false
    })
    useEffect(() => {
        setScroll(props.scroll)
    }, [props.scroll])
    const getTableData = async (params, sort, filter) => {
        // console.log(sort, filter);
        const { current, ...others } = params
        let res = await api.userCenter.role.list({ ...others, currentPage: current })
        if (!res || res.result === null) {
            return { data: [], total: 0, success: true }
        }
        return { data: res.result.records, total: res.result.page.totalRow, success: true };
    }
    const onAdd = () => {
        setState({
            ...state,
            form: {
                description: '',
                id: '',
                name: ''
            },
            dialogAddVisible: true
        })
    }
    // 删除
    const onDelete = async (record, action) => {
        let res = await api.userCenter.role.remove({ id: record.id })
        res && res.success && message.success(res.message || '操作成功')
        action && action.reload()
        // getTableData()
    }
    const onSubmit = async (values) => {
        if (values) {
            setState({
                ...state,
                dialogAddVisible: false
            })
            let params = {
                "authIds": (values.authIds && [...values.authIds]) || [],
                "description": values.description,
                "id": values.id,
                "name": values.name
            }
            let res = ''
            if (values.id) {
                params.id = values.id
                res = await api.userCenter.role.edit({ ...params })
            } else {
                res = await api.userCenter.role.add({ ...params })
            }
            res && res.success && message.success(res.message || '操作成功')
            actionRef.current.reload()
            // getTableData()
            return
        }
        setState({
            ...state,
            dialogAddVisible: false
        })
    }
    return (<><YzhTable
        columns={columns}
        scroll={{
            x: scroll.x,
            y: hasPermission([pCodes.role.add]) ? scroll.y - 390 : scroll.y - 360
        }}
        actionRef={actionRef}
        request={async (params = {}, sort, filter) => getTableData(params, sort, filter)}
        editable={{
            // type: 'multiple',
            onlyOneLineEditorAlertMessage: '只能同时编辑一行',
            onSave: async (k, r) => {
                onSubmit(r)
            },
            actionRender: (row, config, dom) => [dom.save, dom.cancel],
            onDelete: async (k, r) => onDelete(r, actionRef.current)
        }}
        rowKey="id"
        tableExtraRender={() => [
            (hasPermission([pCodes.role.add]) &&
                <Button key="button" icon={<PlusOutlined />} onClick={onAdd} style={{ marginRight: 8 }} type="primary">
                    添加
                </Button>),
        ]}
    />
        {state.dialogAddVisible ?
            <AddRoleDialog {...state.form}
                setAddDialog={onSubmit}
                dialogAddVisible={state.dialogAddVisible} /> : null}
    </>);
};
export default RoleManage;